import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store/index'
import { ElMessage } from "element-plus";

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/Home/index.vue'),
  },
  // 游戏
  {
    path: '/game',
    name: 'game',
    component: () => import('@/views/Game/index.vue'),
  },
  {
    path: '/gameList',
    name: 'gameList',
    component: () => import('@/views/Game/gameList/index.vue'),
  },
  {
    path: '/gameItem',
    name: 'gameItem',
    component: () => import('@/views/Game/gameItem/index.vue'),
  },
  // 道具
  {
    path: '/propsList',
    name: 'propsList',
    component: () => import('@/views/Props/propsList/index.vue'),
  },
  {
    path: '/propsItem',
    name: 'propsItem',
    component: () => import('@/views/Props/propsItem/index.vue'),
  },
  {
    path: '/account',
    name: 'account',
    component: () => import('@/views/Account/index.vue'),
    children: [
      {
        path: '/account/order',
        component: () => import('@/views/Account/order.vue'),
      },
      {
        path: '/account/pay',
        component: () => import('@/views/Account/pay.vue'),
      },
      {
        path: "/account/contact_us",
        component: () => import('@/views/Account/contact_us.vue'),
      },
      {
        path: '/account/about_us',
        component: () => import('@/views/Account/about_us.vue'),
      },
      {
        path: '/account/privacy_policy',
        component: () => import('@/views/Account/privacy_policy.vue'),
      },
      {
        path: '/account/refund_policy',
        component: () => import('@/views/Account/refund_policy.vue'),
      },
      {
        path: '/account',
        redirect: {
          path: '/account/pay',
        }
      }
    ]
  },
  // 404 页面
  {
    path: '/:catchAll(.*)',
    name: 'NotFound',
    component: () => import('@/views/404.vue')
  },
  {
    // 路由重定向
    path: '/',
    redirect: {
      path: '/',
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  // 每次路由跳转之后 新页面加载在x轴和y轴的初始位置
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
})

// 全局前置守卫
router.beforeEach((to, from, next) => {

  if (to.path === '/gameItem' && !store.state.userInfo.access_token) {

    ElMessage({
      message: "Please Login First!",
      type: "warning",
    });

  }
  else if (to.path.match(/^\/account\/(.*)/) && !store.state.userInfo.access_token) {

    ElMessage({
      message: "Please Login First!",
      type: "warning",
    });

  } else {
    next();
  }

});

export default router

